import router, { loadAsyncRoutes, addAsyncRoutes } from '@/router';
import useStore from '@/store';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css'
NProgress.configure({ showSpinner: false }); // 进度环显示/隐藏

// 标记是否已经加载过异步路由
let asyncRoutesLoaded = false;

// 白名单路由
const whiteList = ['/login'];

// 全局前置守卫
router.beforeEach(async (to, from, next) => { 
  NProgress.start();
  const { user } = useStore();
  const hasToken = user.token;
  if(hasToken){
    if (to.path === '/login') {
      next({ path: '/' });
    } else {
  // 如果还没有加载异步路由，则加载它们
  if (!asyncRoutesLoaded) {
    try {
      await loadAsyncRoutes();
      addAsyncRoutes(router);
      asyncRoutesLoaded = true;
      // 重新导航到目标路由
      if (to.path !== '/') {
        next({ ...to, replace: true });
      } else {
        next();
      }
      return;
    } catch (error) {
      console.error('加载异步路由失败:', error);
    }
  }
      next();
    }
  } else {
    // 未登录可以访问白名单页面(登录页面)
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login`);
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});